#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   GameLoad
@Time    :   2023/04/12 15:22:22
@author  :   Eval
@Version :   1.0
@Describe:   加载页面
'''
from pygame.locals import *
from lib.scripts.GC import *
from map.mapManage.mapMgr import *
from lib.scripts.ui.ShowDiaLog import *
import traceback,sys

class GameLoad:
    def __init__(self,parent) -> None:
        import main
        self.parent:main.Run = parent
        self.isActive = True
        self.loadLevel = 0 # 0. 是否正在加载页面, 1.加载完毕->主页菜单 2. 加载页面的事件全部结束,进入游戏
        self.tips = "开始加载资源"
        self.BtnGroups = {
                "closeDuel":{
                    "name":"开始游戏",
                    "function":self.startGame,
                    "pos":None,
                    "index":0  # 动态设置
                },
                # "onlineGame":{
                #     "name":"多人模式",
                #     "function":self.onlineGame,
                #     "pos":None,
                #     "index":0
                # },
                "changeMusic":{
                    "name":"关闭/开启游戏BGM",
                    "function":self.ModifyPlayBGM,
                    "pos":None,
                    "index":0
                },
                "quit":{
                    "name":"退出游戏",
                    "function":self.parent.GameQuit,
                    "pos":None,
                    "index":0  # 动态设置
                }
            }
        # ui偏移量
        self.offX = 50
        self.offY = 0
        # 鼠标悬浮时
        self.currItem = None
        self.currIndex = 0
        self.isCurr = False # 是否悬浮在菜单区域
        # 加载背景图片
        self.GameBG = GC.loadSurface(GC.GC_GlobalScripts["loadBG"])
        self.GameBG = pygame.transform.smoothscale(self.GameBG,(self.parent.win_w,self.parent.win_h))

    def _GameInit(self):
        self.offY = self.parent.win_h //2
        MapMgr.loadMap(self.parent)
        self.parent._GameInit()

    def render(self):
        """渲染加载页面"""
        if not self.isActive:
            return
        self.__render_view()
        # 监听事件
        self.__events()

    def __render_view(self):
        # 加载页面主体背景
        self.parent.win.blit(self.GameBG,(0,0))
        # 渲染左上角的文本信息
        self.parent.GameFont.render_lineText(10,10,text=self.tips,color=(255,255,255),fontSize=14)
        # 资源加载结束之后, 开始渲染按钮
        if self.loadLevel == 1:
            for index,btn in enumerate(self.BtnGroups):
                x = self.offX+(200 - (len(self.BtnGroups[btn]["name"])*14)) //2
                y = self.offY + (index *14) +( index * 30) + 20
                self.parent.GameFont.render_lineText(x,y,text=self.BtnGroups[btn]["name"],color=(255,255,255),fontSize=20)
                self.BtnGroups[btn]["pos"] = (x,y)        # 鼠标悬浮边框
                self.BtnGroups[btn]["index"] = index      # 当前按钮的索引

            if self.currItem is not None:
                pygame.draw.rect(self.parent.win,(200,200,200),(self.currItem["pos"][0]-5,self.currItem["pos"][1]-2,self.parent.GameFont.getTextWidth(self.currItem["name"],20),30),width=2)
                self.parent.GameFont.render_lineText(self.currItem["pos"][0],self.currItem["pos"][1],text=self.currItem["name"],color=(255,100,0),fontSize=20)
            
            if self.isCurr:
                pygame.draw.rect(self.parent.win,(150,150,150),(self.offX,self.offY,240,200),1)
        
    def __events(self):
        pos = pygame.mouse.get_pos()
        # 选项
        if self.loadLevel == 1:
            # self.currItem = None
            if pos[0] >= self.offX and pos[0] < self.offX +240 and pos[1] >= self.offY and pos[1] < self.offY +200:
                self.isCurr = True
                for i in self.BtnGroups:
                    if self.BtnGroups[i]["pos"] is None:
                        continue
                    if pos[1] >= self.BtnGroups[i]["pos"][1] and pos[1] < self.BtnGroups[i]["pos"][1] +24:
                        self.currIndex = self.BtnGroups[i]["index"]
                        self.currItem = self.BtnGroups[list(self.BtnGroups.keys())[self.BtnGroups[i]["index"]]]
                        break
            else:
                self.isCurr = False
                self.currItem = self.BtnGroups[list(self.BtnGroups.keys())[self.currIndex]]

        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif e.type == pygame.MOUSEBUTTONDOWN:
                if pygame.mouse.get_pressed() == (1,0,0):
                    if pos[0] >= self.offX and pos[0] < self.offX +240 and pos[1] >= self.offY and pos[1] < self.offY +200:
                        self.currItem["function"]()

            elif e.type == pygame.KEYDOWN:
                if e.key == pygame.K_UP:
                    self.currIndex -= 1
                    if self.currIndex < 0:
                        self.currIndex = len(self.BtnGroups.keys())-1
                elif e.key == pygame.K_DOWN:
                    self.currIndex += 1
                    if self.currIndex > len(self.BtnGroups.keys())-1:
                        self.currIndex = 0
                elif e.key == pygame.K_RETURN:
                    self.currItem["function"]()

    def startGame(self):
        """进入游戏"""
        self.loadLevel = 2
        self.isActive = False
        
        # 根据取到的全局配置文件给主角添加默认的钥匙数量
        self.parent.GameBag.addItemByName("黄钥匙",int(self.parent.hero.status["yellowKey"]))
        self.parent.GameBag.addItemByName("蓝钥匙",int(self.parent.hero.status["blueKey"]))
        self.parent.GameBag.addItemByName("红钥匙",int(self.parent.hero.status["redKey"]))
        # 增加道具: 怪物手册
        self.parent.GameBag.addItemByName("怪物手册")
        # 随机增加测试道具
        for i in range(20):
            if i% 2 ==0:
                self.parent.GameBag.addItem(22,(2+i)*i)

    def ModifyPlayBGM(self):
        self.parent.GameMusic.ModifyPlayBGM()

    def onlineGame(self):
        ShowDiaLog.showTips("多人联机功能暂未开放",fontSize=20)